import { ref } from 'vue'
import { API_URL } from '../config/apiConfig'
import { addAuthHeader } from './api/apiUtils'
import type { RuleListItem } from '../types'
import { authStore } from './auth/store'
import { useRouter } from 'vue-router'

export function useRuleManagement() {
  const ruleList = ref<RuleListItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  const fetchRuleList = async () => {
    loading.value = true
    error.value = null
    const router = useRouter()
    
    try {
      const response = await fetch(`${API_URL}/demo/rule/list`, addAuthHeader(
        {
          credentials: 'include',
          method: 'GET'
        }
      ))
      
      if (!response.ok) {
        if (response.status === 401 || response.status === 403) {
          // 清除认证状态
          authStore.clearAuth()
          // 重定向到登录页面
          router.push('/')
          return
        }
        throw new Error(`请求失败: ${response.status}`)
      }
      
      ruleList.value = await response.json()
      
      //ruleList.value = data
    } catch (err) {
      console.error('获取规则列表失败:', err)
      error.value = '获取规则列表失败，请重试'
    } finally {
      loading.value = false
    }
  }

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    } catch (err) {
      return dateString
    }
  }

  const deleteRule = async (ruleId: string) => {
    try {
      const response = await fetch(`${API_URL}/demo/rule/${ruleId}`, addAuthHeader({
        method: 'DELETE'
      }))
      
      if (!response.ok) {
        throw new Error(`删除失败: ${response.status}`)
      }
      
      // 删除成功后刷新列表
      await fetchRuleList()
      return true
    } catch (err) {
      console.error('删除规则失败:', err)
      return false
    }
  }

  return {
    ruleList,
    loading,
    error,
    fetchRuleList,
    formatDate,
    deleteRule
  }
}